#include <commands.h>
#include <user.h>
#include <ts7200.h>
#include <defs.h>
#include <curses.h>

void UpdateSwitchDisplay(track *sts) {
  // AcquireLock(SECTION_TERMINAL_TX);
    SaveCursor();
    SetCursorXY(1, 1);
    Printf("State of turn outs\r\n");
    Printf("------------------\r\n");
    int i, j;
    for (i = 1; i < 12; i++) {
      SetCursorXY(1, i + 2);
      Printf("%d: %c   ", i, sts->sw_dir[i]);
    }
    for (j = 3; i < 19; i++, j++) {
      SetCursorXY(8, j);
      Printf("%d: %c   ", i, sts->sw_dir[i]);
    }
    for (i = 153; i < 157; j++, i++) {
      SetCursorXY(8, j);
      Printf("%x: %c   ", i, sts->sw_dir[i]);
    }
    LoadCursor();
  // ReleaseLock(SECTION_TERMINAL_TX);
}

void Sw(track *sts, int switch_number, char switch_direction) {
  FlipSwitch(sts, switch_number, switch_direction);
  UpdateSwitchDisplay(sts);
}

void Stop(track *sts) {
  // AcquireLock(SECTION_TRAIN_TX);
  Putc( COM1, TRAIN_STOP );
  // ReleaseLock(SECTION_TRAIN_TX);
}

void Go(track *sts) {
  // AcquireLock(SECTION_TRAIN_TX);
  Putc( COM1, TRAIN_GO );
  // ReleaseLock(SECTION_TRAIN_TX);
}

void Tr(track *sts, int train_number, int train_speed) {
  // AcquireLock(SECTION_TRAIN_TX);
  Putc( COM1, train_speed );
  Putc( COM1, train_number );
  // ReleaseLock(SECTION_TRAIN_TX);
  sts->tr_speed[train_number] = train_speed;
}

void Rv(track *sts, int train_number) {
  // AcquireLock(SECTION_TRAIN_TX);
  Putc(COM1, 0);
  Putc(COM1, train_number);
  // ReleaseLock(SECTION_TRAIN_TX);
  Delay(5);
  // AcquireLock(SECTION_TRAIN_TX);
  Putc(COM1, TRAIN_REVERSE);
  Putc(COM1, train_number);
  // ReleaseLock(SECTION_TRAIN_TX);
  Delay(5);
  // AcquireLock(SECTION_TRAIN_TX);
  Putc(COM1, sts->tr_speed[train_number]);
  Putc(COM1, train_number);
  // ReleaseLock(SECTION_TRAIN_TX);
}

void FlipSwitch(track *sts, int switch_number, char switch_direction) {
  // AcquireLock(SECTION_TRAIN_TX);
  if (switch_direction == 'S')
    Putc(COM1, TRAIN_SW_STRAIGHT);
  else
    Putc(COM1, TRAIN_SW_CURVED);
  Putc(COM1, switch_number);
  // ReleaseLock(SECTION_TRAIN_TX);
  // // AcquireLock(SECTION_TRAIN_TX);
  // Putc(COM1, TRAIN_SOLENOID_OFF);
  // // ReleaseLock(SECTION_TRAIN_TX);
  sts->sw_dir[switch_number] = switch_direction;
}
